package com.skynet.whwpro.Alipay;/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import com.alibaba.druid.util.StringUtils;
import com.skynet.whwpro.bean.BeanDyb;
import com.skynet.whwpro.bean.BeanJyjlb;
import com.skynet.whwpro.bean.BeanSjzcb;
import com.skynet.whwpro.bean.BeanWpgzb;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.entity.Record;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CrossOriginFilter;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import java.util.List;
import java.util.UUID;

/**
 * 向小程序前端提供web接口
 *
 * @author alipay.demo
 */
@At("/auth")
@IocBean
@Ok("json:full")
@Filters(@By(type = CrossOriginFilter.class))
public class UserAuthController {

    @Inject
    private Dao dao;

    @Inject
    private UserAuthService userAuthService;

    @At
    @Ok("json")
    public UserInfo authUser(@Param("authCode") String authCode) throws Exception {
        return userAuthService.authUser(authCode);
    }

    @At
    @Ok("json")
    public QueryResult getHistoryDd(@Param("wyid") String wyid, @Param("pageNum") int pageNum, @Param("pageSize") int pageSize) throws Exception {
        Pager pager = dao.createPager(pageNum, pageSize);
        Cnd cnd = Cnd.where("xsdid", "=", wyid);
        cnd.and("zt", "=", "1").desc("pgrksj");
        pager.setRecordCount(dao.count(BeanJyjlb.class, cnd));
        return new QueryResult(dao.query(BeanJyjlb.class, cnd, pager), pager);
    }

    @At
    @Ok("json")
    public long getHistoryDdCount(@Param("wyid") String wyid) throws Exception {
        Cnd cnd = Cnd.where("xsdid", "=", wyid);
        cnd.and("zt", "=", "1");
        return dao.count(BeanJyjlb.class, cnd);
    }

    @At
    @Ok("json")
    public long getMemberListcount(@Param("wyid") String wyid) throws Exception {
        Cnd cnd = Cnd.where("xsdid", "=", wyid);
        cnd.and("zt", "=", "1").desc("pgrksj");
        return dao.count(BeanDyb.class, cnd);
    }

    @At
    @Ok("json")
    public QueryResult getMemberList(@Param("wyid") String wyid, @Param("pageNum") int pageNum, @Param("pageSize") int pageSize) throws Exception {
        Pager pager = dao.createPager(pageNum, pageSize);
        Cnd cnd = Cnd.where("xsdid", "=", wyid);
        cnd.and("zt", "=", "1").desc("pgrksj");
        pager.setRecordCount(dao.count(BeanDyb.class, cnd));
        return new QueryResult(dao.query(BeanDyb.class, cnd, pager), pager);
    }


    /*
    @At("/SjInsert")
    @POST
    @Ok("json")
    public void addUser(@Param("dydata") String data,
                        @Param("wyid") String wyid) throws Exception {
   //先取authCode 再去userinfo 再取userid
        BeanDyb bean = Json.fromJson(BeanDyb.class, data);
        if (Strings.isNotBlank(wyid)) {
            bean.setWyid(wyid);
        }
        dao.insert(bean);
    }
     */

    @At("/SjInsert")
    @Ok("json")
    public Object addUser(@Param("authCode") String authCode, @Param("sjid") String sjid) {
        //先取authCode 再去userinfo 再取userid
        UserInfo uerinfo = null;
        try {
            uerinfo = userAuthService.authUser(authCode);
        } catch (Exception e) {
            e.printStackTrace();
            return new Record().set("error", e.getMessage());
        }
        String userid = uerinfo.getUserId();
        BeanDyb bean = new BeanDyb();
        bean.setDyuserid(userid);
        bean.setXsdid(sjid);
        bean.setWyid(UUID.randomUUID().toString().replaceAll("-", ""));
        try {
            dao.insert(bean);
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userid);
            return userInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return new Record().set("error", e.getMessage());
        }

    }

    @At("/verifyOrder")
    @Ok("json")
    public Record verifyOrder(@Param("orderID") String orderID) {
        Record re = new Record();
        if (StringUtils.isEmpty(orderID)) {
            re.put("flag", false);
            re.put("msg", "参数为空");
            return re;
        }
        List<Record> jylist = dao.query("yhbzxcx_jyjlb", Cnd.where("wyid", "=", orderID));
        if (jylist != null && jylist.size() > 0) {
            if (jylist.get(0).getString("zt").equals("0")) {
                re.put("flag", true);
                re.put("msg", "");
                return re;
            } else {
                re.put("flag", false);
                re.put("msg", "订单已支付");
                return re;
            }
        } else {
            re.put("flag", true);
            re.put("msg", "");
            return re;
        }
    }



     /*
     @At("/addOrder")
     @Ok("json")
     public Record addOrder(@Param("authCode") String authCode, @Param("orderData") String orderData) {
         //先取authCode 再去userinfo 再取userid
         Record re = new Record();
         String userid= "";
         try {
             Record bean = Json.fromJson(Record.class, orderData);
             if(StringUtils.isEmpty(bean.getString("ddid"))){
                 re.put("flag",false);
                 re.put("msg","订单编号为空");
                 return re;
             }
             List<Record> jylist = dao.query("yhbzxcx_jyjlb", Cnd.where("wyid","=",bean.getString("ddid")));
             if(jylist != null && jylist.size() > 0){
                 if(jylist.get(0).getString("zt").equals("0")){
                     BeanJyjlb jyjlb = new BeanJyjlb();
                     jyjlb.setJestr(Double.parseDouble(bean.getString("je")));
                     jyjlb.setSlstr(Integer.parseInt(bean.getString("sl")));
                     if(!authCode.equals("null")){
                         UserInfo uerinfo = userAuthService.authUser(authCode);
                         userid = uerinfo.getUserId();
                     }
                     jyjlb.setWyid(bean.getString("ddid"));
                     jyjlb.setBuyerid(userid);
                     jyjlb.setZt("1");
                     jyjlb.setWp(bean.getString("wp"));
                     jyjlb.setDw(bean.getString("dw"));
                     jyjlb.setXsdid(jylist.get(0).getString("xsdid"));
                     dao.update(jyjlb);
                     re.put("flag",true);
                     re.put("msg","交易完成");
                     return re;
                 }else{
                     re.put("flag",false);
                     re.put("msg","订单已支付，请勿重复支付");
                     return re;
                 }
             }else{
                 re.put("flag",false);
                 re.put("msg","订单创建有误");
                 return re;
             }
         }catch (Exception e){
             e.printStackTrace();
             re.put("flag",false);
             re.put("msg","交易失败");
             return re;
         }
     }

      */

    @At("/addOrder")
    @Ok("json")
    //买家authcode  订单里含有卖家iD
    public Record addOrder(@Param("authCode") String authCode, @Param("orderData") String orderData) {
        //先取authCode 再去userinfo 再取userid
        Record re = new Record();
        String userid = "";
        try {
            Record bean = Json.fromJson(Record.class, orderData);
            if (StringUtils.isEmpty(bean.getString("ddid"))) {
                re.put("flag", false);
                re.put("msg", "订单编号为空");
                return re;
            }
            List<Record> jylist = dao.query("yhbzxcx_jyjlb", Cnd.where("wyid", "=", bean.getString("ddid")));
            if (jylist != null && jylist.size() > 0) {
                if (jylist.get(0).getString("zt").equals("0")) {
                    BeanJyjlb jyjlb = new BeanJyjlb();
                    jyjlb.setJe(Double.parseDouble(bean.getString("je")));
                    jyjlb.setSl(Integer.parseInt(bean.getString("sl")));
                    if (!authCode.equals("null")) {
                        UserInfo uerinfo = userAuthService.authUser(authCode);
                        userid = uerinfo.getUserId();
                    }
                    jyjlb.setWyid(bean.getString("ddid"));
                    jyjlb.setBuyerid(userid);
                    jyjlb.setZt("1");
                    jyjlb.setWp(bean.getString("wp"));
                    jyjlb.setDw(bean.getString("dw"));
                    jyjlb.setXsdid(jylist.get(0).getString("xsdid"));
                    jyjlb.setSellerid(jylist.get(0).getString("sellerid"));
                    jyjlb.setWpbh(jylist.get(0).getString("wpbh"));
                    jyjlb.setLxfs(jylist.get(0).getString("lxfs"));
                    dao.update(jyjlb);
                    List<Record> wplist = dao.query("yhbzxcx_wpgzb", Cnd.where("spbh", "=", jylist.get(0).getString("wpbh")));
                    if (wplist == null && wplist.size() == 0) {
                        BeanWpgzb wpgzb1 = new BeanWpgzb();
                        wpgzb1.setSpbh(jylist.get(0).getString("wpbh"));
                        wpgzb1.setZl(bean.getString("zl"));
                        wpgzb1.setGg(bean.getString("gg"));
                        wpgzb1.setMs(bean.getString("ms"));
                        wpgzb1.setScqymc(bean.getString("scqymc"));
                        wpgzb1.setJyzt("1");
                        wpgzb1.setCxzt("0");
                        dao.insert(wpgzb1);
                    } else if (wplist.size() == 1 && bean.getString("cxzt") == "1") {
                        BeanWpgzb wpgzb2 = new BeanWpgzb();
                        wpgzb2.setSpbh(jylist.get(0).getString("wpbh"));
                        wpgzb2.setZl(bean.getString("zl"));
                        wpgzb2.setGg(bean.getString("gg"));
                        wpgzb2.setMs(bean.getString("ms"));
                        wpgzb2.setScqymc(bean.getString("scqymc"));
                        wpgzb2.setJyzt("1");
                        wpgzb2.setCxzt("1");
                        dao.update(wpgzb2);
                    }
                    re.put("flag", true);
                    re.put("msg", "交易完成");
                    return re;

                } else {
                    re.put("flag", false);
                    re.put("msg", "订单已支付，请勿重复支付");
                    return re;
                }
            } else {
                re.put("flag", false);
                re.put("msg", "订单创建有误");
                return re;
            }
        } catch (Exception e) {
            e.printStackTrace();
            re.put("flag", false);
            re.put("msg", "交易失败");
            return re;
        }
    }


}
